<template>
  <ly-dialog
    v-model="visible"
    :title="$t('route.capitalProject') + '--' +'新增'"
    width="1250px"
    fullscreen
    :confirm="handleConfirm"
    :cancel="handleCancel"
    :before-close="() => {$emit('update:visible', false)}"
    @open="handleOpen"
  >
    <template #operation>
      <el-button
        type="primary"
        icon="el-icon-circle-plus-outline"
        @click="handlePush()"
      >增加一行</el-button>
      <el-button
        type="primary"
        icon="el-icon-circle-plus-outline"
        @click="handleCopy()"
      >复制一行</el-button>
      <el-button
        type="primary"
        icon="el-icon-delete"
        class="deleted-button"
        @click="handleBatchDelete()"
      >
        批量删除
      </el-button>
    </template>
    <ly-form
      size="mini"
      class="mini-form"
      style="width:100%"
      :model="temp"
      @submit.native.prevent
    >
      <el-row>
        <el-col :span="5">
          <el-form-item
            label="投入日期"
            prop="orderDate"
          >
            <el-date-picker
              v-model="temp.orderDate"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item
            label="项目"
            prop="project"
          >
            <el-select
              v-model="temp.project"
              clearable
              placeholder="请选择项目"
              @change="handleChange($event,'project')"
            >
              <el-option
                v-for="item in projectList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item
            label="进展"
            prop="progress"
          >
            <el-select
              v-model="temp.progress"
              clearable
              placeholder="请选择进展"
              @change="handleChange($event,'progress')"
            >
              <el-option
                v-for="item in progressList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </ly-form>
    <client-table
      ref="table"
      :style="{ height: `${commonLayoutHeight}px`}"
      :columns="capitalAddColumnDef"
      :data="tableData"
      show-summary
      @selection-change="handleSelectionChange"
      @cell-value-changed="handleCellValueChanged"
    />
  </ly-dialog>
</template>

<script>
import NP from 'number-precision'
import { mapState } from 'vuex'
import { addOne } from '@/api/capital'

export default {
  name: 'CapitalAddDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: undefined
    },
    typeList: {
      type: Array,
      default: undefined
    },
    projectList: {
      type: Array,
      default: undefined
    },
    progressList: {
      type: Array,
      default: undefined
    }
  },
  data() {
    return {
      temp: {
        orderDate: '',
        modifyTime: '',
        project: '',
        projectName: '',
        progress: '',
        progressName: '',
        type: '',
        typeName: ''
      },
      restTemp: {
        orderDate: '',
        modifyTime: '',
        project: '',
        projectName: '',
        progress: '',
        progressName: '',
        type: '',
        typeName: ''
      },
      tableData: [],
      multipleSelection: [],
      capitalAddColumnDef: [
        {
          headerName: '任务名称',
          field: 'itemName',
          singleClickEdit: true,
          type: 'stringColumn',
          headerClass: 'my-class'
        },
        {
          headerName: '投入金额',
          field: 'investPrice',
          showSummary: true,
          type: 'numberColumn',
          headerClass: 'my-class'
        },
        {
          headerName: '收益金额',
          field: 'orderPrice',
          type: 'numberColumn',
          showSummary: true,
          headerClass: 'my-class'
        },
        {
          headerName: '类型',
          field: 'type',
          type: 'selectionColumn',
          cellEditorParams: {
            list: [],
            props: { label: 'name', value: 'id' },
            select: (node, row) => {
              setTimeout(() => {
                node.data.type = row.id
                node.data.typeName = row.name
                node.setData(node.data)
              }, 300)
            }
          }
        },
        {
          headerName: '利润',
          field: 'profit',
          showSummary: true
        },
        {
          headerName: '利润率(%)',
          field: 'profitRate'
        },
        {
          headerName: '备注',
          type: 'stringColumn',
          field: 'remarks'
        }
      ]
    }
  },
  computed: {
    ...mapState('app', {
      commonLayoutHeight: state => state.height.clientHeight - 190
    })
  },
  watch: {
    typeList(val) {
      const tableColumnDef = this.capitalAddColumnDef.find(column => column.field === 'type')
      tableColumnDef.cellEditorParams.list = val
    }
  },
  methods: {
    handleOpen() {
      this.tableData = []
      this.temp = Object.assign({}, this.restTemp)
      setTimeout(() => {
        this.handlePush()
      }, 200)
      // 键盘绑定事件
      const that = this
      document.addEventListener('keydown', that.bindingKeydown)
    },
    async handleConfirm() {
      const capitalLists = this.$refs.table.getData()
      const list = capitalLists.filter(item => item.itemName === '' && item.investPrice === '' && item.orderPrice === '')
      if (list.length > 0) {
        return this.$message({
          showClose: true,
          message: '必选项未填！！！',
          type: 'warning',
          center: true
        })
      }
      const params = Object.assign({}, this.temp)
      params.capitalLists = capitalLists
      const result = await addOne('getCapitalAdd', params)
      if (result.code === 200) {
        this.setVisible(false)
        this.$notify({
          title: '成功',
          message: '新增成功',
          type: 'success',
          duration: 2000
        })
        this.$emit('add-data')
      }
    },
    // 下键事件
    bindingKeydown(event) {
      if (event.code === 'ArrowDown') {
        this.handleCopy()
      }
    },
    // 新增
    handlePush() {
      const addRow = this.capitalAddColumnDef.reduce((acc, curr) => {
        acc[curr.field] = ''
        return acc
      }, {})
      const addRows = [addRow]
      addRows[0].taxRate = '0.035'
      this.$refs.table.addRows(addRows)
      this.$refs.table.redrawRows()
      this.$refs.table.selectRow(addRow)
      this.$refs.table.syncSummaryRow(this.$refs.table.getData())
    },
    // 复制
    handleCopy() {
      const addRow = Object.assign({}, this.multipleSelection[0])
      const addRows = [addRow]
      this.$refs.table.addRows(addRows)
      this.$refs.table.redrawRows()
      this.$refs.table.selectRow(addRow)
      this.$refs.table.syncSummaryRow(this.$refs.table.getData())
    },
    // 删除
    handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          showClose: true,
          message: '请勾选要删除项',
          type: 'warning',
          center: true
        })
        return
      }
      this.$refs.table.removeRows(this.multipleSelection)
      this.$refs.table.syncSummaryRow(this.$refs.table.getData())
    },
    // 双击修改
    handleCellValueChanged(e) {
      // 计算规则
      // 利润 = 收益金额 — 投入金额
      // 利润率 = (利润 / 收益金额) × 100%
      if (e.value !== e.oldValue) {
        if (e.data.orderPrice) {
          e.data.profit = NP.round(NP.minus(e.data.orderPrice, e.data.investPrice), 2)
          e.data.profitRate = NP.round(NP.times(NP.divide(e.data.profit, e.data.orderPrice), 100), 2) + '%'
          this.$refs.table.redrawRows()
        }
      }
      this.$refs.table.syncSummaryRow(this.$refs.table.getData())
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleChange(id, val) {
      if (val === 'progress') {
        const list = this.progressList.filter(item => item.id === id)
        if (list.length > 0) {
          this.temp.progressName = list[0].name
        } else {
          this.temp.progressName = ''
        }
      } else if (val === 'type') {
        const list = this.typeList.filter(item => item.id === id)
        if (list.length > 0) {
          this.temp.typeName = list[0].name
        } else {
          this.temp.typeName = ''
        }
      } else {
        const list = this.projectList.filter(item => item.id === id)
        if (list.length > 0) {
          this.temp.projectName = list[0].name
        } else {
          this.temp.projectName = ''
        }
      }
    },
    handleCancel() {
      this.setVisible(false)
    },
    setVisible(flag) {
      this.$emit('update:visible', flag)
    }
  }
}
</script>

<style>
</style>
